<template>
    <toolbar/>
    <codemirror
      v-model="code"
      placeholder="Code goes here..."
      :style="{ height: '800px'}"
      :autofocus="true"
      :indent-with-tab="true"
      :tab-size="2"
      :extensions="extensions"
      @ready="handleReady"
      @change="log('change', $event)"
      @focus="log('focus', $event)"
      @blur="log('blur', $event)"
    />
  </template>
  
  <script>
    import toolbar from '@/components/Problem/toolBar.vue'
    import { defineComponent, ref, shallowRef,onMounted,computed, watch} from 'vue'
    import { Codemirror } from 'vue-codemirror'
    import { javascript } from '@codemirror/lang-javascript'
    import { oneDark } from '@codemirror/theme-one-dark'
    import emitter from '@/util/emit'
    import {mainStore} from '@/store'
    import { storeToRefs } from 'pinia';
    import {Base64} from 'js-base64'
    export default defineComponent({
      components: {
        Codemirror,
        toolbar
      },
    setup() {
        const code = ref(``)
        const themeAndlang=ref({})
        // const extensions = [javascript(), oneDark]
        const extensions = computed(() => {
        const result = []
        if (themeAndlang.value.language) {
          result.push(themeAndlang.value.language())
        }else{
          result.push(javascript() )
        }
        if (themeAndlang.value.theme) {
          result.push(themeAndlang.value.theme)
        }else{
          result.push(oneDark)
        }
        return result
      })
        // Codemirror EditorView instance ref
        const view = shallowRef()
        const handleReady = (payload) => {
          view.value = payload.view
        }
  
        // Status is available at all times via Codemirror EditorView
        const getCodemirrorStates = () => {
          const state = view.value.state
          const ranges = state.selection.ranges
          const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
          const cursor = ranges[0].anchor
          const length = state.doc.length
          const lines = state.doc.lines
          // more state info ...
          // return ...
        }

        onMounted(()=>{
          
          emitter.on('update',(e)=>{
            themeAndlang.value=e;

          })
        })
        
        //监听代码
        const mainStoreI = mainStore();
        watch(code,(newValue)=>{

          mainStoreI.codeInfo.sourceCode=Base64.encode(newValue)
                })
  
        return {
          code,
          extensions,
          handleReady,
          log: console.log
        }
      }
    })
  </script>

